package cn.itsource.pethome.basic.service.impl;

import cn.itsource.pethome.basic.constant.PetHomeConstant;
import cn.itsource.pethome.basic.service.IVerificationCodeService;
import cn.itsource.pethome.basic.util.SendMsgUtil;
import cn.itsource.pethome.basic.util.StrUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class VerificationCodeServiceImpl implements IVerificationCodeService {

    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public void sendRegisterMobileCode(String phone) {
        //1.产生随机4位的验证码  JK82
        String code = StrUtils.getComplexRandomString(4);
        //通过手机号码在redis中获取对应的验证码    JK82:21312433542423
        String codeValue = (String) redisTemplate.opsForValue().get(PetHomeConstant.REGISTER_VERIFICATION_CODE+":"+phone);
        if(!StringUtils.isEmpty(codeValue)){
            //获取第一次的毫秒时间
            Long beginTimer = Long.valueOf(codeValue.split(":")[1]);
            if(System.currentTimeMillis()-beginTimer<60*1000){
                throw new RuntimeException("一分钟以内不能重复获取验证码!!!");
            }
            //如果没有走抛异常就证明验证码依然在5分钟以内，但是超过了1分钟
            code = codeValue.split(":")[0];
        }
        //2.把验证码存储到redis中，并且有效期是5分钟
        redisTemplate.opsForValue().set(PetHomeConstant.REGISTER_VERIFICATION_CODE+":"+phone,
                code+":"+System.currentTimeMillis(),5, TimeUnit.MINUTES);
        String content = "尊敬的用户，你的验证码为:"+code+",请在5分钟以内完成验证操作!!";
        System.out.println(content);

    }

    public static void main(String[] args) {
        String str = "dfsdgf";
        System.out.println(StringUtils.isEmpty(str));
    }
}
